/*
 * Created by shuukusunokigiggle on 2017/5/21.
 */
import java.util.*;
/*
    中缀表达式转后缀表达式
 */

public class InfixToSuffix {
    private Stack<String> stack;
    private List<String> list1,list2;
    private String message,Message="";

    public InfixToSuffix() {
        stack = new Stack<String>();
        list1 = new ArrayList<String>();
        list2 = new ArrayList<String>();
    }

    public void evaluate(String expr) {
        String token;
        StringTokenizer tokenizer = new StringTokenizer(expr);

        while (tokenizer.hasMoreTokens()) {
            token = tokenizer.nextToken();

            if (token.equals("("))
                stack.push(token);
            else if (token.equals("+") || token.equals("-")) {
                while (!stack.empty()){
                    if("(".equals(stack.peek())){
                        break;
                    }else list1.add(stack.pop());
                }
                stack.push(token);
            }else if (token.equals("*") || token.equals("/")) {
                if(!stack.empty()) {
                    if (stack.peek().equals("*") || stack.peek().equals("/")) {
                        boolean add = list1.add(stack.pop());
                        stack.push(token);
                    } else stack.push(token);
                }else stack.push(token);
            }
            else if (token.equals(")")) {
                while (!stack.peek().equals("(")) {
                    list1.add(stack.pop());
                }
                stack.pop();
            }else list1.add(token);
        }
        while (!stack.empty()) {
            list1.add(stack.pop());
        }
        ListIterator<String > li = list1.listIterator();
        while (li.hasNext()) {
            Message += li.next() + " ";
            li.remove();
        }
        message = Message;
    }

    //返回转换后的结果
    public String getMessage(){
        return message;
    }
}

